$(function() {
    var cart2 = {
        getPayMethod: function() {
            //支付方式
            $(document).on('click', '.change-payment .consignee-item', function(){
    			 var $this = $(this);
    			  var tempN = $(".change-payment .consignee-item").index($this);
    			 if($this.hasClass("item-selected")){
    				   return false;
    				 }else{
    					 $(".change-payment .consignee-item").removeClass("item-selected");
    					 $this.addClass("item-selected");
    					 $(".payment-tip").hide();
    					 $(".payment-tip").eq(tempN).show();
    				  }
    		})

            $.ajax({
                url: wsCommon.host + '/api/payments/getMethodByPlatformTag',
                dataType: wsCommon.jsonType,
                data: {
                    platformTag: 1
                },
                success: function(res) {
                    if(res.code == 1) {
                        var data = res.data;

                        var payMethodTpl = '';
                        // var payMethodTpl2 = '';
                        $.each(data, function(index, item) {
                            var aclass = '';
                            var bclass = '';
                            if (index == 0) {
                                aclass = 'item-selected';
                                bclass = 'show';
                            }
                            payMethodTpl += '<li>\
                                                 <div class="consignee-item '+aclass+'" datahint="'+item.description+'" data-id="'+item.id+'">\
                                                    <img src="'+item.logoUrl+'">\
                                                     <span title="'+item.paymentMethodName+'" >'+item.paymentMethodName+'</span><b></b>\
                                                 </div>\
                                                </li>';
                            // payMethodTpl2 += '<div  class="payment-tip '+bclass+'"><ul>';
                            // $.each(item.paymentMethodList, function(indexDir, itemDir) {
                            //     var imgTpl = '';
                            //     if(itemDir.logoUrl) {
                            //         imgTpl += '<img src="'+itemDir.logoUrl+'" style="height:18px"/>';
                            //     }
                            //     payMethodTpl2 += '<li><input type="radio" name="payment" id="pay_app_id_cash'+index.toString()+indexDir.toString()+'" value="'+itemDir.paymentMethodName+'" data-id="'+itemDir.id+'">\
                            //                                <label for="pay_app_id_cash'+index.toString()+indexDir.toString()+'">'+itemDir.paymentMethodName+'&nbsp;'+imgTpl+'</label>\
                            //                         </li>';
                            //
                            // });
                            // payMethodTpl2 += '</ul></div>';
                        })
                        $('[data-role="payMethod"] .change-payment').html(payMethodTpl);
                        // $('[data-role="payMethod"]').append(payMethodTpl2);
                        // $('[data-role="payMethod"]').append('<button type="button" class="btn btn-caution action-confirm-payment" style="margin-left:10px;margin-top:10px;"><span><span>确认支付方式</span></span></button>');
                    }
                },
                error: function() {
                    // console.log('支付方式接口返回失败');
                }
            })
        },
        cartList: function(da) {
            $.ajax({
                url: wsCommon.host + '/api/cart/cartPay',
                dataType: wsCommon.jsonType,
                data: da,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            cart2.cart2PromotionInfo = res.data;
                            var buyInfoList = res.data.buyInfoList;
                            var payResultInfo = res.data.payResultInfo;

                            var cartListTpl = '';
                            $.each(buyInfoList, function(index, item) {
                                var params = JSON.parse(item.params);
                                cartListTpl += '<tr class="cart-product last">\
                                                  <td class="p-info">\
                                                    <div class="p-title"><a target="_blank" href="../info.html?goodsId='+item.goodsId+'&catId='+params.catId+'">'+params.productName+'</a></div>\
                                                  </td>\
                                                  <td class="p-price">¥'+params.price+'</td>\
                                                  <td>'+item.count+'</td>\
                                                  <td class="p-discount">¥'+item.saveMoney+'</td>\
                                                  <td class="p-integral" data-result="jf">'+item.score+'</td>\
                                                  <td class="p-subtotal" data-result="spje">¥'+item.subtotalPrice+'</td>\
                                                </tr>';
                            })
                            $('[data-role="cartList"]').html(cartListTpl);
                            cart2.resetResult(payResultInfo.totalMoney, payResultInfo.freight, payResultInfo.payMoney);

                            var jf = 0;
                            $.each($('[data-result="jf"]'), function(index, item) {
                                jf += Number($(item).html());
                            })
                            $('[data-role="jf"]').html(jf);

                            // 订单优惠
                            var orderRuleApplyInfos = res.data.payResultInfo.orderRuleApplyInfos != null ? res.data.payResultInfo.orderRuleApplyInfos : [];
                            var orderRuleApplyInfosTpl = '';
                            if(orderRuleApplyInfos.length == 0) {
                                orderRuleApplyInfosTpl += '<li>无</li>'
                            } else {
                                $.each(orderRuleApplyInfos, function(index, item) {
                                    orderRuleApplyInfosTpl += '<li><b>['+item.tag+']</b>'+item.ruleName+'</li>';
                                });
                            }

                            $('[data-role="ddyh"]').html(orderRuleApplyInfosTpl);

                            // 积分抵扣信息
                            $('[data-role="zongeTips"]').html(payResultInfo.pointUseInfo.scoreSaveMessage);
                            $('[data-role="zdkdkje"]').html(payResultInfo.pointUseInfo.maxSaveMoneyOrRateWithScore);
                            $('[data-role="maxScore"]').html(payResultInfo.pointUseInfo.needPoint);
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },

        handleInvoice: function() {
            //发票
    		$(":text").focus(function(){
    		  this.select();
    		 });
    		$(document).on('click', ".change-invoice .consignee-item", function(){
    			 var $this = $(this);
    			 if($this.hasClass("item-selected")){
    				   return false;
    				 }else{
    					 $(".change-invoice .consignee-item").removeClass("item-selected");
    					 $this.addClass("item-selected");
    					 if($this.hasClass("need-ivo")){
    						$(".invoice-con").show();
    					 }else{ $(".invoice-con").hide(); }
    				 };
    		})


    		$('#invoice-tit-list')
    			.delegate('.invoice-item','click',function(e){
                    var $this = $(this);
                    // 删除
                    if($(e.target).hasClass('del-tit')) {
                        var id = $(e.target).attr('data-id');
                        cart2.delInvoice(id,function() {
                            iosOverlay({
                                text: "删除成功!",
                                duration: 1000
                            });
                            $('#for_tax_content').find('option').eq(0).prop('selected', true);
                            $this.closest('.invoice-item').remove();
                        })

                    } else {
                        var taxContent = $this.attr('data-content');
                        $('#for_tax_content').find('option[value="'+taxContent+'"]').prop('selected', true);
                        $this.addClass('invoice-item-selected').siblings().removeClass('invoice-item-selected');
                    }

    			})
               .delegate('.invoice-item','mouseover',function(){
    				$(this).addClass('hover');
    			})
    		   .delegate('.invoice-item','mouseout',function(){
    				$(this).removeClass('hover');
    			})
    		   .delegate('.btns','mouseover',function(){
    				$(this).parents('.invoice-item').addClass('btn-hover');
    			})
    			.delegate('.btns','mouseout',function(){
    				$(this).parents('.invoice-item').removeClass('btn-hover');
    			})
    		   .delegate('.invoice-item .itxt','blur',function(e){//失去焦点回复初始值及状态
                //    if($(e.target).hasClass('for_tax_content') || $(e.target).is('option')) return;
    			// 	var _r = $(this).attr('data-r');
    			// 	var _val = $(this).val();
    			// 	// var _isEmpty = isEmpty(_val);
    			// 	if(_r){//编辑的输入框
                   //
    			// 		if($(this).parents('.invoice-item').hasClass('btn-hover')) return;//点击本身的按钮失去焦点，返回
    			// 		$('.invoice-item-selected .btns .edit-tit').removeClass('hide').next().addClass('hide');
    			// 		$(this).attr("readonly",true);
    			// 	}
    			})
    			.delegate('.edit-tit','click',function(){// 点击编辑按钮 当前按钮隐藏 输入框变成可编辑状态
                    var taxContent = $(this).attr('data-tax');
                    $('#for_tax_content').find('option[value="'+taxContent+'"]').prop('selected', true);
    				$(this).addClass('hide').next().removeClass('hide');
    				$(this).parent().prev().find('.fore2 .itxt').removeAttr('readonly').focus();
    			})
    			.delegate('.update-tit','click',function(){
                    var $this = $(this);
                    var taxContent = $('#for_tax_content').find('option:selected').val();
                    var contentId = $('#for_tax_content').find('option:selected').attr('data-id');
                    var taxCompany = $this.parent('.btns').prev().find('input').val();
                    if(content == '' || taxCompany == '') {
                        iosOverlay({
                            text: "发票内容或者发票抬头不能为空!",
                            duration: 1500
                        });
                        return;
                    }
                    var taxType = 'company';
                    var taxId = $this.attr('data-id');
                    cart2.editInvoice(taxId,taxCompany,contentId,taxType,function(res) {
                        iosOverlay({
                            text: "修改成功!",
                            duration: 1000
                        });
                        $this.closest('.invoice-item').attr('data-content', res.taxContent);
                        $this.closest('.invoice-item').find('input').prop('value', res.taxCompany).attr('data-r', res.taxCompany);
                        $this.closest('.invoice-item').find('.edit-tit').attr('data-tax', res.taxContent);
                        $('#for_tax_content').find('option[value="'+res.taxContent+'"]').prop('selected', true);
                        $this.addClass('hide').prev().removeClass('hide');
        				$this.parent().prev().find('.fore2 .itxt').attr("readonly",true).blur();
                    });
    			})
    			.delegate('.save-tit','click',function(){
                    var inputCon = $('#save-invoice-input').val();
                    var taxContent = $('#for_tax_content').find('option:selected').val();
                    var contentId = $('#for_tax_content').find('option:selected').attr('data-id');
                    var taxType = 'company';
                    if(inputCon == '' || !contentId) {
                        iosOverlay({
                            text: "发票内容或者发票抬头不能为空!",
                            duration: 1500
                        });
                    } else {
                        cart2.addInvoice(inputCon,contentId,taxType,function(res) {
                            iosOverlay({
                                text: "添加成功!",
                                duration: 1000
                            });
                            var tpl = '<div class="invoice-item invoice-item-selected" style="cursor:pointer" data-content="'+res.taxContent+'" data-taxid="'+res.taxId+'">\
                                        <div id="invoice-1" style="cursor:pointer">\
                                            <span class="fore2" name="usualInvoiceList">\
                                                <input type="text" class="itxt" style="cursor:pointer" value="'+res.taxCompany+'" data-r="'+res.taxCompany+'"  readOnly="true"><b></b></span>\
                                        </div>\
                                        <div class="btns">\
                                        <span class="lnklike edit-tit" data-tax="'+res.taxContent+'" data-id="'+res.taxId+'">编辑</span>\
                                        <span class="lnklike update-tit hide" data-id="'+res.taxId+'">保存</span>\
                                        <span class="lnklike del-tit" data-id="'+res.taxId+'" data-memberId="'+res.memberId+'">删除</span>\
                                        </div>\
                                </div>';
                                $('#invoice-tit-list .invoice-tit-lists').append(tpl);
                                $('#save-invoice-input').val('');
                                $('#save-invoice').hide();
                                $('#add-invoice').show();
                        })
                    }

    				// alert("保存内容  更新界面")
    			})
    			.delegate('.cancel-tit','click',function(){
    				$('#add-invoice').show();
    				$('#save-invoice').hide();
    			});
        },

        // 罗列发票
        listInvoice: function() {
            $.ajax({
                url: wsCommon.host + '/api/memberTax/queryByMemberId',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            var data = res.data;
                            var memberTaxList = data.memberTaxList == null ? [] : data.memberTaxList;
                            var taxContentList = data.taxContentList == null ? [] : data.taxContentList;

                            var tpl = '';
                            $.each(memberTaxList, function(index, item) {
                                // invoice-item-selected
                                tpl += '<div class="invoice-item" style="cursor:pointer" data-content="'+item.taxContent+'" data-taxCompany="'+item.taxCompany+'" data-taxid="'+item.taxId+'">\
                                            <div id="invoice-1" style="cursor:pointer">\
                                                <span class="fore2" name="usualInvoiceList">\
                                                    <input type="text" class="itxt" style="cursor:pointer" value="'+item.taxCompany+'" data-r="'+item.taxCompany+'"  readOnly="true">\ <b></b></span>\
                                            </div>\
                                            <div class="btns">\
                                                <span class="lnklike edit-tit" data-tax="'+item.taxContent+'" data-id="'+item.taxId+'">编辑</span>\
                                                <span class="lnklike update-tit hide" data-id="'+item.taxId+'">保存</span>\
                                                <span class="lnklike del-tit" data-id="'+item.taxId+'" data-memberId="'+item.memberId+'">删除</span>\
                                            </div>\
                                    </div>';
                            })
                            $('#invoice-tit-list .invoice-tit-lists').html(tpl);

                            // 发票内容
                            var taxContentListTpl = '<option>选择发票内容</option>';
                            $.each(taxContentList, function(index, item) {
                                taxContentListTpl += '<option value="'+item.taxContent+'" data-id="'+item.contentId+'">'+item.taxContent+'</option>';
                            })
                            $('#for_tax_content').html(taxContentListTpl);
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {
                    // console.log('罗列发票接口返回失败');
                }
            })
        },

        // 添加发票
        addInvoice: function(taxCompany,contentId,taxType,cb) {

            $.ajax({
                url: wsCommon.host + '/api/memberTax/addMemberTax',
                dataType: wsCommon.jsonType,
                data: {
                    taxCompany: taxCompany,
                    contentId: contentId,
                    taxType: taxType
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            // 超出限制的处理
                            cb(res.data.memberTax);
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    } else {
                        iosOverlay({
                            text: "添加失败!",
                            duration: 1500
                        });
                    }
                },
                error: function() {
                    // console.log('添加发票接口返回失败');
                }
            })
        },

        // 删除发票
        delInvoice: function(id,cb) {

            $.ajax({
                url: wsCommon.host + '/api/memberTax/delete',
                dataType: wsCommon.jsonType,
                data: {
                    taxId: id
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            cb();
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    } else {
                        iosOverlay({
                            text: "删除失败!",
                            duration: 1500
                        });
                    }
                },
                error: function() {
                    // console.log('删除发票接口返回失败');
                }
            })
        },

        // 编辑发票
        editInvoice: function(taxId,taxCompany,contentId,taxType,cb) {

            $.ajax({
                url: wsCommon.host + '/api/memberTax/editMemberTax',
                dataType: wsCommon.jsonType,
                data: {
                    memberId: 2,
                    taxId: taxId,
                    taxCompany: taxCompany,
                    contentId: contentId,
                    taxType: taxType
                },
                success: function(res) {
                    if(res.code == 1) {
                        cb(res.data.memberTax);
                    } else {
                        iosOverlay({
                            text: "编辑失败!",
                            duration: 1500
                        });
                    }
                },
                error: function() {
                    // console.log('编辑发票接口返回失败');
                }
            })
        },

        // 收货地址
        getArrData: function() {

            // 切换地址更新显示
            $(document).on('click',"#change_shipping .consignee-item,.addr-detail",function(){
                // console.log(333);
                var $this = $(this);
    			var tempC = $(this).parents(".ui-switchable-panel");
    			$(this).parents(".ui-switchable-panel").addClass("ui-switchable-panel-selected").siblings().removeClass("ui-switchable-panel-selected");
    			tempC.children(".consignee-item").addClass("item-selected");
    			tempC.siblings().children(".consignee-item").removeClass("item-selected");

                $('[data-cart2="addr"]').html('寄送至：'+$this.attr('data-area') + $this.attr('data-editaddr')+' 收货人：'+$this.attr('data-editname')+' ' + $this.attr('data-editmobile'));
    		})

            $.ajax({
                url: wsCommon.host + '/api/memberAddrs/queryByMemberId',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    // console.log(res)
                    if(res.code == 1) {
                        if(res.result) {
                            var memberAddrsList = res.data.memberAddrsList == null ? [] : res.data.memberAddrsList;
                            var regionsList = res.data.regionsList == null ? [] : res.data.regionsList;

                            var regionsListTpl = '<option data-id="-1">请选择</option>';
                            $.each(regionsList, function(index, item) {
                                regionsListTpl += '<option data-id="'+item.regionId+'">'+item.localName+'</option>';
                            })
                            $('#notice_pop1').find('.x-select').html(regionsListTpl);
                            $('#notice_pop').find('.x-select').html(regionsListTpl);

                            cart2.renderMemberAddrsList(memberAddrsList);
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {
                    // console.log('收货地址显示接口返回失败');
                }
            })
        },
        renderMemberAddrsList: function(memberAddrsList) {
            var memberAddrsListTpl = '';
            if(memberAddrsList.length == 0) {
                memberAddrsListTpl += '无';
                $('.addr_sel_show').hide();
            } else {
                if($('.addr_sel_hide').is(':hidden')) {
                    $('.addr_sel_show').show();
                }
                $.each(memberAddrsList, function(index, item) {
                    if(index == 0) {
                        memberAddrsListTpl += '<li class="ui-switchable-panel ui-switchable-panel-selected defaultship" style="display: list-item;">\
                                                    <div class="consignee-item item-selected" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                        <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                    </div>\
                                                    <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                        <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                        <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                        <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                        <span class="addr-default">默认地址</span>\
                                                    </div>\
                                                    <div class="op-btns">\
                                                    <span class="lnklike action-edit-address" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                    <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                    </div>\
                                                </li>';
                        $('[data-cart2="addr"]').html('寄送至：'+item.area + item.addr+' 收货人：'+item.name+' ' + (item.mobile ? item.mobile : item.tel));
                    } else {
                        memberAddrsListTpl += '<li class="ui-switchable-panel" style="display: list-item;">\
                                                <div class="consignee-item" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                    <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                </div>\
                                                <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                    <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                    <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                    <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                    <span class="addr-default">默认地址</span>\
                                                </div>\
                                                <div class="op-btns">\
                                                    <span class="lnklike action-default-address" data-addrId="'+item.addrId+'">设为默认地址</span>\
                                                    <span class="lnklike action-edit-address" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                    <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                </div>\
                                            </li>';
                    }

                })
            }

            $('#change_shipping').html(memberAddrsListTpl);
        },
        renderMemberAddrsListAdd: function(memberAddrsList) {
            var memberAddrsListTpl = '';
            if(memberAddrsList.length == 0) {
                memberAddrsListTpl += '无';
                $('.addr_sel_show').hide();
            } else {
                if($('.addr_sel_hide').is(':hidden')) {
                    $('.addr_sel_show').show();
                }
                $.each(memberAddrsList, function(index, item) {
                    if(index == 0) {
                        if(item.defAddr == 1) {
                            memberAddrsListTpl += '<li class="ui-switchable-panel ui-switchable-panel-selected defaultship" style="display: list-item;">\
                                                        <div class="consignee-item item-selected" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                        </div>\
                                                        <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                            <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                            <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                            <span class="addr-default">默认地址</span>\
                                                        </div>\
                                                        <div class="op-btns">\
                                                        <span class="lnklike action-edit-address" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                        <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                        </div>\
                                                    </li>';
                            $('[data-cart2="addr"]').html('寄送至：'+item.area + item.addr+' 收货人：'+item.name+' ' + (item.mobile ? item.mobile : item.tel));
                        } else {
                            memberAddrsListTpl += '<li class="ui-switchable-panel ui-switchable-panel-selected" style="display: list-item;">\
                                                        <div class="consignee-item item-selected" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                        </div>\
                                                        <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                            <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                            <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                        </div>\
                                                        <div class="op-btns">\
                                                        <span class="lnklike action-default-address" data-addrId="'+item.addrId+'">设为默认地址</span>\
                                                        <span class="lnklike action-edit-address" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                        <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                        </div>\
                                                    </li>';
                        }

                    } else {
                        if(item.defAddr == 1) {
                            memberAddrsListTpl += '<li class="ui-switchable-panel defaultship" style="display: list-item;">\
                                                        <div class="consignee-item" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                        </div>\
                                                        <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                            <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                            <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                            <span class="addr-default">默认地址</span>\
                                                        </div>\
                                                        <div class="op-btns">\
                                                        <span class="lnklike action-edit-address" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                        <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                        </div>\
                                                    </li>';
                        } else {
                            memberAddrsListTpl += '<li class="ui-switchable-panel" style="display: list-item;">\
                                                        <div class="consignee-item" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span limit="8" title="'+item.addrAlias+'">'+item.addrAlias+'</span><b></b>\
                                                        </div>\
                                                        <div class="addr-detail" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">\
                                                            <span class="addr-name" title="'+item.name+'">'+item.name+'&nbsp;</span>\
                                                            <span class="addr-info" title="'+item.area+' '+item.addr+'">'+item.area+' '+item.addr+'&nbsp;</span>\
                                                            <span class="addr-tel">'+(item.mobile ? item.mobile : item.tel)+'</span>\
                                                        </div>\
                                                        <div class="op-btns">\
                                                        <span class="lnklike action-default-address" data-addrId="'+item.addrId+'">设为默认地址</span>\
                                                        <span class="lnklike action-edit-address" data-area="'+item.area+'" data-addrId="'+item.addrId+'" data-editName="'+item.name+'" data-editRegion="'+item.regionId+'" data-editAddr="'+item.addr+'" data-editMobile="'+item.mobile+'" data-editTel="'+item.tel+'" data-editAddrAlias="'+(item.addrAlias?item.addrAlias:'')+'">编辑</span>\
                                                        <span class="lnklike action-delete-address" data-addrId="'+item.addrId+'">删除</span>\
                                                        </div>\
                                                    </li>';
                            $('[data-cart2="addr"]').html('寄送至：'+item.area + item.addr+' 收货人：'+item.name+' ' + (item.mobile ? item.mobile : item.tel));
                        }
                    }

                })
            }

            $('#change_shipping').html(memberAddrsListTpl);
        },
        // 新增收货地址
        addArr: function() {
            $(document).on('click',".add-address-btn",function(){
                // reset data
                $('[data-add="name"]').val('');
                $('[data-add="region"]').find('option').eq(0).prop('selected', true);
                $('[data-add="addr"]').val('');
                $('[data-add="mobile"]').val('');
                $('[data-add="tel"]').val('');
                $('[data-add="addrAlias"]').val('');

    		   $(".cover").show();
    		   $("#notice_pop1").show();
    		})

            $(document).on('click', '[data-role="addAdd"]', function() {
                var name = $('[data-add="name"]').val();
                if(name == '') {
                    iosOverlay({
                		text: "收货人不能为空!",
                        duration: 1500
                	});
                    return;
                }
                var region = $('[data-add="region"]').find('option:selected').attr('data-id');
                if(region == -1) {
                    iosOverlay({
                        text: "所在地区不能为空!",
                        duration: 1500
                    });
                    return;
                }
                var addr = $('[data-add="addr"]').val();
                if(addr == '') {
                    iosOverlay({
                		text: "详细地址不能为空!",
                        duration: 1500
                	});
                    return;
                }

                var mobile = $('[data-add="mobile"]').val();
                var tel = $('[data-add="tel"]').val();
                var reg = /^((13[0-9])|(15[^4,\D])|(18[0,3-9]))\d{8}$/;
                if(mobile == '') {
                    iosOverlay({
                		text: "手机号码不能为空!",
                        duration: 1500
                	});
                    return;
                } else if(!reg.test(mobile)) {
                    iosOverlay({
                		text: "手机号码格式不正确!",
                        duration: 1500
                	});
                    return;
                }
                var addrAlias = $('[data-add="addrAlias"]').val();

                $.ajax({
                    url: wsCommon.host + '/api/memberAddrs/addMemberAddrs',
                    dataType: wsCommon.jsonType,
                    data: {
                        regionId: region,
                        name: name,
                        addr: addr,
                        mobile: mobile,
                        tel: tel,
                        addrAlias: addrAlias
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                $("#notice_pop1").hide();
                        		$(".cover").hide();
                                iosOverlay({
                                    text: "添加成功!",
                                    duration: 1000
                                });
                                // reset data
                                $('[data-add="name"]').val('');
                                $('[data-add="region"]').find('option').eq(0).prop('selected', true);
                                $('[data-add="addr"]').val('');
                                $('[data-add="mobile"]').val('');
                                $('[data-add="tel"]').val('');
                                $('[data-add="addrAlias"]').val('');

                                cart2.renderMemberAddrsListAdd(res.data.memberAddrsList);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('收货地址显示接口返回失败');
                    }
                })
            })
        },
        // 编辑收货地址
        editArr: function() {
            $(document).on('click',".action-edit-address",function(){
    		   $(".cover").show();
    		   $("#notice_pop").show();
    		})
            var addrId = null;
            $(document).on('click',".action-edit-address",function(){
                var $this = $(this);
                $('[data-edit="name"]').val($this.attr('data-editName'));
                $('[data-edit="region"]').find('option[data-id="'+$this.attr('data-editRegion')+'"]').prop('selected', true);
                $('[data-edit="addr"]').val($this.attr('data-editAddr'));
                $('[data-edit="mobile"]').val($this.attr('data-editMobile'));
                if($this.attr('data-editTel') != 'null') $('[data-edit="tel"]').val($this.attr('data-editTel'));
                if($this.attr('data-editaddralias') != 'null') $('[data-edit="addrAlias"]').val($this.attr('data-editaddralias'));
                addrId = $this.attr('data-addrId')

    		   $(".cover").show();
    		   $("#notice_pop").show();
    		})
            $(document).on('click', '[data-role="saveAdd"]', function() {
                var name = $('[data-edit="name"]').val();
                if(name == '') {
                    iosOverlay({
                		text: "收货人不能为空!",
                        duration: 1500
                	});
                    return;
                }
                var region = $('[data-edit="region"]').find('option:selected').attr('data-id');
                if(region == -1) {
                    iosOverlay({
                		text: "所在地区不能为空!",
                        duration: 1500
                	});
                    return;
                }
                var addr = $('[data-edit="addr"]').val();
                if(addr == '') {
                    iosOverlay({
                		text: "详细地址不能为空!",
                        duration: 1500
                	});
                    return;
                }

                var mobile = $('[data-edit="mobile"]').val();
                var tel = $('[data-edit="tel"]').val();
                var reg = /^((13[0-9])|(15[^4,\D])|(18[0,5-9]))\d{8}$/;
                if(mobile == '') {
                    iosOverlay({
                		text: "手机号码不能为空!",
                        duration: 1500
                	});
                    return;
                } else if(!reg.test(mobile)) {
                    iosOverlay({
                		text: "手机号码格式不正确!",
                        duration: 1500
                	});
                    return;
                }

                var addrAlias = $('[data-edit="addrAlias"]').val();

                $.ajax({
                    url: wsCommon.host + '/api/memberAddrs/editMemberAddrs',
                    dataType: wsCommon.jsonType,
                    data: {
                        addrId: addrId,
                        regionId: region,
                        name: name,
                        addrId: addrId,
                        mobile: mobile,
                        addr: addr,
                        tel: tel,
                        addrAlias: addrAlias
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                $("#notice_pop").hide();
                        		$(".cover").hide();
                                iosOverlay({
                            		text: "修改成功!",
                                    duration: 1000
                            	});
                                // reset data
                                $('[data-edit="name"]').val('');
                                $('[data-edit="region"]').find('option').eq(0).prop('selected', true);
                                $('[data-edit="addr"]').val('');
                                $('[data-edit="mobile"]').val('');
                                $('[data-edit="tel"]').val('');
                                $('[data-edit="addrAlias"]').val('');
                                cart2.renderMemberAddrsList(res.data.memberAddrsList);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('编辑收货地址接口返回失败');
                    }
                })
            })
        },
        // 删除收货地址
        delArr: function() {
            $(document).on('click', '.action-delete-address', function() {
                var addrId = $(this).attr('data-addrId');
                $.ajax({
                    url: wsCommon.host + '/api/memberAddrs/delete',
                    dataType: wsCommon.jsonType,
                    data: {
                        addrId: addrId
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                iosOverlay({
                                    text: "删除成功!",
                                    duration: 1000
                                });
                                cart2.renderMemberAddrsList(res.data.memberAddrsList);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('删除收货地址接口返回失败');
                    }
                })
            })

        },
        // 设置默认收货地址
        setDefaultArr: function() {
            $(document).on('click',".action-default-address",function(){
                var addrId = $(this).attr('data-addrId');
                $.ajax({
                    url: wsCommon.host + '/api/memberAddrs/setDefAddr',
                    dataType: wsCommon.jsonType,
                    data: {
                        addrId: addrId
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                iosOverlay({
                            		text: "设置默认地址成功!",
                                    duration: 1000
                            	});
                                cart2.renderMemberAddrsList(res.data.memberAddrsList);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('设置默认收货地址接口返回失败');
                    }
                })

    		})

        },
        // 配送时间
        distributeTime: function() {
            var chooseDom = null;
            //送货时间
    		$(document).on('click',".action-delivery-time",function(){
                $(this).hide();
                $('[data-role="distributeTime"]').show();
                $('[data-role="saveTime"]').show();
    		})
            $(document).on('click', '[data-role="ctime"]', function() {
                $('[data-role="distributeTime"]').hide();
                $('[data-role="saveTime"]').hide();
                $('.action-delivery-time').show();
                var row = $('#d_time_show').attr('row');
                var col = $('#d_time_show').attr('col');
                $('#time_s_btn').find('.checkbox:not(.disabled)').removeClass('selected').html('可选');
                $('#time_s_btn>ul').eq(row).find('li').eq(col).addClass('selected').html('已选');
            })
            $(document).on('click', '[data-role="stime"]', function() {
                $('#d_time_show').html($('#time_s_btn').find('.selected').attr('val'));
                $('[data-role="distributeTime"]').hide();
                $('[data-role="saveTime"]').hide();
                $('.action-delivery-time').show();
                $('#d_time_show').attr('row', $('#time_s_btn .selected').attr('row'));
                $('#d_time_show').attr('col', $('#time_s_btn .selected').attr('col'));
            })
            $.ajax({
                url: wsCommon.host + '/api/order/shipTime',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        var shipHeader = res.data.shipHeader;
                        var timeRangeTitle = res.data.timeRangeTitle;
                        var shipList = res.data.shipList;
                        var shipTime = res.data.shipTime;

                        var distributeTimeTpl = '<dl class="th">';
                        $.each(shipHeader, function(index, item) {
                            if(index == 0) {
                                distributeTimeTpl += '<dt>'+item+'</dt><dd class="date">';
                            } else {
                                if(index == 7) {
                                    distributeTimeTpl += '<span row="-1" col="'+(index-1)+'" class="last">'+item.split(':')[0]+'<br>'+item.split(':')[1]+'</span>';
                                } else {
                                    distributeTimeTpl += '<span row="-1" col="'+(index-1)+'" class="">'+item.split(':')[0]+'<br>'+item.split(':')[1]+'</span>';
                                }
                            }
                        })
                        distributeTimeTpl += '</dd><dd class="time">';
                        $.each(timeRangeTitle, function(index, item) {
                            if(index == 2) {
                                distributeTimeTpl += '<span row="0" col="'+(index-1)+'" class="">'+item+'</span>';
                            } else {
                                distributeTimeTpl += '<span row="0" col="'+(index-1)+'" class="last">'+item+'</span>';
                            }
                        })
                        distributeTimeTpl += '</dd></dl><div class="data" id="time_s_btn">';
                        var textFlag = true;
                        $.each(shipList, function(index, item) {
                            distributeTimeTpl += '<ul>';
                            $.each(item, function(indexDir, itemDir) {
                                if(itemDir == '') {
                                    distributeTimeTpl += '<li class="checkbox disabled" >'+itemDir+'</li>';
                                } else {
                                    // if(textFlag) {

                                    //     textFlag = false;
                                    //     distributeTimeTpl += '<li class="checkbox" row="'+index+'" col="'+(indexDir)+'" val="'+shipHeader[indexDir+1].split(':')[0] + '('+shipHeader[indexDir+1].split(':')[1]+')'+' '+timeRangeTitle[index]+'"  range="'+timeRangeTitle[index]+'">已选</li>';
                                    // } else {
                                        distributeTimeTpl += '<li class="checkbox" row="'+index+'" col="'+(indexDir)+'" val="'+shipHeader[indexDir+1].split(':')[0] + '('+shipHeader[indexDir+1].split(':')[1]+')'+' '+timeRangeTitle[index]+'"  range="'+timeRangeTitle[index]+'">'+itemDir+'</li>';
                                    // }

                                }
                            })
                            distributeTimeTpl += '</ul>';
                        });
                        distributeTimeTpl += '</div>';
                        $('[data-role="distributeTime"]').html(distributeTimeTpl);
                        $('#d_time_show').html(shipTime);
                        var shipTimeArr = shipTime.split(' ');
                        var colIndex = shipTimeArr[0].split('[')[0];
                        var rowNum = 0;
                        var colNum = 0;

                        $.each($('.date').find('span'), function(index, item) {
                            if($(item).html().indexOf(colIndex) != -1) {
                                colNum = index;
                            }
                        })

                        $.each($('.time').find('span'), function(index, item) {
                            if($(item).html().indexOf(shipTimeArr[1]) != -1) {
                                rowNum = index;
                            }
                        })
                        $('#time_s_btn').find('ul').eq(rowNum).find('li').eq(colNum).html('已选').addClass('selected');
                    }
                },
                error: function() {
                    // console.log('配送时间接口接口返回失败');
                }
            })
        },
        // 确认支付方式
        submitPay: function() {
            $(document).on('click', '.change-pay-btn', function() {
                $(this).hide();
                $('[data-role="paySubmit"]').hide();
                $('[data-role="payMethod"]').show();
            })

            $(document).on('click', '.action-confirm-payment', function() {
                var id = $('[data-role="payMethod"]').find('input:checked').attr('data-id');
                var value = $('[data-role="payMethod"]').find('input:checked').val();
                if(!id) {
                    iosOverlay({
                        text: "请选择支付方式!",
                        duration: 1000
                    });
                } else {
                    $('[data-role="paySubmit"]').attr('data-id', id);
                    $('[data-role="paySubmit"]').find('i').html(value).end().show();
                    $('[data-role="payMethod"]').hide();
                    $('.change-pay-btn').show();
                }

            })
        },

        // 获取会员积分，优惠券，余额
        getUserBbInfo: function() {
            $.ajax({
                url: wsCommon.host + '/api/memberBenefits/getMemberBenefits',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            var advance = res.data.advance != null ? res.data.advance : 0;
                            var point = res.data.point != null ? res.data.point : 0;
                            var couponList = res.data.couponList != null ? res.data.couponList : [];
                            $('[data-role="yue"]').html(advance);
                            $('[data-role="dqzhjf"]').html(point).attr('data-total', point);
                            $('[data-role="sjjf"]').attr('data-max', point);

                            var couponListTpl = '<option data-cpnsId="-1">-- 选择优惠券 --</option>';
                            $.each(couponList, function(index, item) {
                                if(item.fit) {
                                    $('[data-yhq="name"]').html(item.memcCode +'-'+item.cpnsName);
                                    $('[data-role="useArea"]').removeClass('fold');
                                    $('[data-role="cancelCoupon"]').attr('data-cpnsid', item.cpnsId).attr('data-memcCode', item.memcCode).attr('data-cpnsName', item.cpnsName);
                                    couponListTpl += '<option value="'+item.cpnsName+'" data-cpnsId="'+item.cpnsId+'" data-memcCode="'+item.memcCode+'" selected="selected">'+item.cpnsName+'</option>';
                                } else {
                                    couponListTpl += '<option value="'+item.cpnsName+'" data-cpnsId="'+item.cpnsId+'" data-memcCode="'+item.memcCode+'">'+item.cpnsName+'</option>';
                                }
                            })
                            if(couponList.length == 0) {
                                $('#for_select_coupon').prop('disabled', 'disabled')
                            }
                            $('#for_select_coupon').html(couponListTpl);
                            cart2.cartList({
                                cartIdentInfos: wsCommon.getCookie('cartIdentInfos')
                            });
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {
                    // console.log('获取会员积分，优惠券，余额接口返回失败');
                }
            })

            // 积分验证
            var kdkDom = $('[data-role="kdk"]');
            $('[data-role="sjjf"]').on('keyup', function() {
                var $this = $(this);
                var tmptxt = $this.val();
                $this.val(tmptxt.replace(/\D|^0/g,''));
                var max = $this.attr('data-max');
                if(Number($this.val()) > max) {
                    $this.val(max);
                    kdkDom.html('¥' + (Number($this.val())*0.1).toFixed(1));
                } else {
                    kdkDom.html('¥' + (Number($this.val())*0.1).toFixed(1));
                }
            })

            // 积分确认使用
            $(".action-confirm-score").click(function(){
                var sjjfVal = $('[data-role="sjjf"]').val();
                if(sjjfVal == '') {
                    iosOverlay({
                        text: "请输入积分!",
                        duration: 1000
                    });
                    return;
                } else {
                    $.ajax({
                        url: wsCommon.host + '/api/cart/cartPayPointUse',
                        dataType: wsCommon.jsonType,
                        data: {
                            cartIdentInfos: wsCommon.getCookie('cartIdentInfos'),
                            point: sjjfVal
                        },
                        success: function(res) {
                            if(res.code == 1) {
                                if(res.result) {
                                    cart2.cart2PromotionInfo = res.data;
                                    var totalPointe = Number($('[data-role="dqzhjf"]').attr('data-total')) - Number(sjjfVal);
                                    $('[data-role="dqzhjf"]').html(totalPointe);
                                    $('[data-role="sdkjf"]').html(sjjfVal);
                                    $('[data-role="sdkje"]').html($('[data-role="kdk"]').html())
                                    $(this).parents(".scoreinput").addClass("fold");
                                    $(".usedscore").removeClass("fold");

                                    cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                                } else {
                                    wsCommon.setCookie('go_back_link', window.location.href);
                                    window.location.href = './passport-login.html';
                                }
                            }
                        },
                        error: function() {
                            // console.log('购物车显示接口返回失败');
                        }
                    })

                }
            })


            // 取消积分
            $(".action-cancel-score").click(function(){
                var $this = $(this);
                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPayPointCancel?',
                    dataType: wsCommon.jsonType,
                    data: {
                        cartIdentInfos: wsCommon.getCookie('cartIdentInfos')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                cart2.cart2PromotionInfo = res.data;
                                $('[data-role="dqzhjf"]').html($('[data-role="dqzhjf"]').attr('data-total'));
                                $this.parents(".usedscore").addClass("fold");
                                $(".scoreinput").removeClass("fold");
                                $('.action-input-score').val('');
                                $('[data-role="kdk"]').html('¥0.0')

                                cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('购物车显示接口返回失败');
                    }
                })
            })

            // 余额
            $('[data-role="inputYe"]').on('click', function() {
                if($(this).prop('checked')) {
                    var total = Number($('[data-role="zje"]').html().substring(1));
                    var current = Number($('[data-role="yue"]').html());
                    var advance = 0;
                    if(current > 0) {
                        if(total > current) {
                            advance = current;
                        } else {
                            advance = total;
                        }

                        $.ajax({
                            url: wsCommon.host + '/api/cart/cartPayAdvanceUse',
                            dataType: wsCommon.jsonType,
                            data: {
                                cartIdentInfos: wsCommon.getCookie('cartIdentInfos'),
                                advance: advance
                            },
                            success: function(res) {
                                if(res.code == 1) {
                                    if(res.result) {
                                        cart2.cart2PromotionInfo = res.data;
                                        $('[data-role="inputYeUse"]').show();
                                        cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                                    } else {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                    }
                                }
                            },
                            error: function() {
                                // console.log('余额使用接口返回失败');
                            }
                        })
                    }
                    $('[data-role="inputYeUse"] font').html(advance);

                } else {
                    var current = Number($('[data-role="yue"]').html());
                    if(current > 0) {
                        $.ajax({
                            url: wsCommon.host + '/api/cart/cartPayAdvanceCancel',
                            dataType: wsCommon.jsonType,
                            success: function(res) {
                                if(res.code == 1) {
                                    if(res.result) {
                                        cart2.cart2PromotionInfo = res.data;
                                        $('[data-role="inputYeUse"]').hide();
                                        cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                                    } else {
                                        wsCommon.setCookie('go_back_link', window.location.href);
                                        window.location.href = './passport-login.html';
                                    }
                                }
                            },
                            error: function() {
                                // console.log('余额取消使用接口返回失败');
                            }
                        })
                    }
                }
            })
        },
        // 优惠券使用
        useCoupon: function() {
            $(document).on('click', '[data-role="useCoupon"]', function() {
                var cpnsid = $('#for_select_coupon').find("option:selected").attr('data-cpnsid');
                if(cpnsid == -1) {
                    iosOverlay({
                        text: "请选择优惠券!",
                        duration: 1000
                    });
                    return;
                }
                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPayCouponUse',
                    dataType: wsCommon.jsonType,
                    data: {
                        cartIdentInfos: wsCommon.getCookie('cartIdentInfos'),
                        cpnsId: cpnsid
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                var couponApplyInfos = res.data.payResultInfo.couponApplyInfos[0];
                                if(!couponApplyInfos.fit) {
                                    iosOverlay({
                                        text: "优惠券使用失败!",
                                        duration: 1000
                                    });
                                    return;
                                }
                                cart2.cart2PromotionInfo = res.data;

                                $('[data-yhq="name"]').html(couponApplyInfos.memcCode +'-'+couponApplyInfos.cpnsName);
                                $('[data-role="useArea"]').removeClass('fold');
                                $('[data-role="cancelCoupon"]').attr('data-cpnsid', couponApplyInfos.cpnsId).attr('data-memcCode', couponApplyInfos.memcCode).attr('data-cpnsName', couponApplyInfos.cpnsName);

                                cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('优惠券使用接口返回失败');
                    }
                })
            })
        },
        cancelCoupon: function() {
            $(document).on('click', '[data-role="cancelCoupon"]', function() {
                var $this = $(this);
                var cpnsid = $this.attr('data-cpnsid');
                var cpnsName = $this.attr('data-cpnsName');
                var memcCode = $this.attr('data-memcCode');
                $.ajax({
                    url: wsCommon.host + '/api/cart/cartPayCouponCancel',
                    dataType: wsCommon.jsonType,
                    data: {
                        cartIdentInfos: wsCommon.getCookie('cartIdentInfos'),
                        // cpnsId: cpnsid,
                        // cpnsName: cpnsName,
                        // memcCode: memcCode
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                cart2.cart2PromotionInfo = res.data;
                                $('[data-yhq="name"]').html('');
                                $('[data-role="useArea"]').addClass('fold');
                                $('[data-role="cancelCoupon"]').removeAttr('data-cpnsid').removeAttr('data-memcCode').removeAttr('data-cpnsName');
                                $('#for_select_coupon').find("option").eq(0).prop('selected', true);

                                cart2.resetResult(res.data.payResultInfo.totalMoney, res.data.payResultInfo.freight, res.data.payResultInfo.payMoney);
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        }
                    },
                    error: function() {
                        // console.log('优惠券取消接口返回失败');
                    }
                })
            })
        },
        resetResult: function(spje, yf, zje) {
            $('[data-role="spje"]').html('¥'+spje);
            $('[data-role="yf"]').html('¥'+yf);
            $('[data-role="zje"]').html('¥'+zje);
        },
         // 提交订单
        sendOrder: function() {
            $('.action-submit-order').on('click', function() {
                // 地址
                var addrDom = $('#change_shipping').find('li.ui-switchable-panel-selected');
                if(addrDom.length == 0) {
                    iosOverlay({
                        text: "请填写收货地址!",
                        duration: 1000
                    });
                    return;
                }
                var addrId = addrDom.find('.consignee-item').attr('data-addrid');

                //送货时间
                if(!$('#d_time_save').is(':hidden')) {
                    iosOverlay({
                        text: "请选择收货时间!",
                        duration: 1000
                    });
                    return;
                }
                var deliveryTime = $('#d_time_show').html();

                // 支付方式
                // if(!$('.action-confirm-payment').is(':hidden')) {
                //     iosOverlay({
                //         text: "请选择支付方式!",
                //         duration: 1000
                //     });
                //     return;
                // }
                var payment = $('.change-payment .item-selected').attr('data-id');

                // 发票
                var isTax = null;
                var taxIndex = $('.change-invoice').find('.item-selected').parents('li').index();
                if(taxIndex == 0) {
                    isTax = false;
                    var taxId = 0;
                } else {
                    isTax = true;
                    var taxType = 'company';
                    var taxSelectDom = $('#invoice-tit-list .invoice-item-selected');
                    if(taxSelectDom.length == 0) {
                        iosOverlay({
                            text: "请填写发票信息!",
                            duration: 1000
                        });
                        return;
                    } else {
                        var taxId = taxSelectDom.attr('data-taxid');
                    }
                }

                //订单备注
                var memo = $('.action-remark-textarea').val();

                var promotionInfo = cart2.cart2PromotionInfo;

                if(cart2.isEmptyObject(promotionInfo)) {
                    iosOverlay({
                        text: "请稍后提交!",
                        duration: 1000
                    });
                    return;
                }

                var req = {
                    payment: payment,
                    addrId: addrId,
                    shipTime: deliveryTime,
                    isTax: isTax,
                    taxId: Number(taxId),
                    memo: memo,
                    promotionInfo: promotionInfo
                }
                // console.log(JSON.stringify(req));
                $.ajax({
                    url: wsCommon.host + '/api/orders/createOrder',
                    dataType: wsCommon.jsonType,
                    data: {
                        req: JSON.stringify(req)
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(res.result) {
                                var orderInfo = {
                                    orderId: res.data.orderId,
                                    // itemnum: res.data.itemnum,
                                    // addr: res.data.shipArea + res.data.shipAddr,
                                    // getGoodsPerson: '(收货人:'+res.data.shipName+' 手机:'+res.data.shipMobile+')',
                                    // shipTime: res.data.shipTime + '配送',
                                    // paymentName: res.data.paymentName,
                                    // payment: res.data.payment,
                                    // finalAmount: res.data.finalAmount,
                                    // paymentType: res.data.paymentType
                                };
                                // console.log(orderInfo, JSON.stringify(orderInfo));

                                wsCommon.setCookie('orderInfo', JSON.stringify(orderInfo));

                                iosOverlay({
                                    text: "订单生成成功，正在跳转!",
                                    duration: 1000,
                                    onbeforehide: function() {
                                        window.location.href = './cart3.html';
                                    }
                                });
                            } else {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                            }
                        } else {
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function() {
                        // console.log('接口返回失败');
                    }
                })
                // console.log(addrId, deliveryTime, payment, isTax, taxId, memo, promotionInfo);
            })
        },
        cart2PromotionInfo: {},
        isEmptyObject: function(e) {
            var t;
            for (t in e)
                return !1;
            return !0
        },
        init: function() {
            this.getArrData();
            this.handleInvoice();
            this.getPayMethod();
            this.listInvoice();
            this.addArr();
            this.editArr();
            this.delArr();
            this.setDefaultArr();
            this.distributeTime();
            this.submitPay();
            this.getUserBbInfo();
            this.useCoupon();
            this.cancelCoupon();
            this.sendOrder();
        }
    }

    cart2.init();
})
